package com.dsbj.wx.api.service;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.wx.api.utils.PropertyUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class WxUserService {


	@Resource(name = "httpsRestTemplate")
	private RestTemplate httpsRestTemplate;

	public ResponseMessage getOpenIdByCode(String code) {
		System.out.println("getOpenIdByCode:"+code);
		if(StringUtils.isBlank(code)){
			return ResponseMessage.error("code不能为空");
		}
		String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", PropertyUtil.getAppid(),PropertyUtil.getAppsecret(),code);
		Map<String,String> map = new HashMap<>();
		map = httpsRestTemplate.getForObject(url,HashMap.class);
		String openId = map.get("openid");
		if(StringUtils.isBlank(openId)){
			return ResponseMessage.error("获取openid失败");
		}
		return ResponseMessage.ok(openId);
	}
}
